package com.ukefu.webim.web.handler.api.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import static org.elasticsearch.index.query.QueryBuilders.termQuery;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.es.OrdersCommentRepository;
import com.ukefu.webim.service.es.WorkOrdersRepository;
import com.ukefu.webim.service.repository.AttachmentRepository;
import com.ukefu.webim.service.repository.DataEventRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.handler.api.request.SearchData;
import com.ukefu.webim.web.model.DataEvent;
import com.ukefu.webim.web.model.OrdersComment;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.WorkOrders;

@RestController
@RequestMapping("/api/workorders/comment")
@Api(value = "工单服务", description = "回复工单")
public class ApiWorkOrdersCommentController extends Handler{
	
	@Value("${web.upload-path}")
    private String path;

	@Autowired
	private AttachmentRepository attachementRes;

	@Autowired
	private WorkOrdersRepository workOrdersRepository;
	
	@Autowired
	private OrdersCommentRepository ordersCommentRes ;

	@Autowired
	private DataEventRepository dataEventRes ;
	

	@Autowired
	private WorkOrdersRepository workOrdersRes ;
	
	@Autowired
	private UserRepository userRepository;
	
	/**
	 * 回复工单
	 * @param request
	 * @param q	
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping( method = RequestMethod.PUT)
	@Menu(type = "apps" , subtype = "workorders" , access = true)
	@ApiOperation("回复工单")
    public ResponseEntity<RestResult> list(HttpServletRequest request ,@Valid String id,@Valid OrdersComment comment, @Valid MultipartFile[] files) throws IOException {
		RestResult result = new RestResult(RestResultType.OK) ; 
		if(!StringUtils.isBlank(id)){
			WorkOrders workOrders = workOrdersRepository.findByIdAndOrgi(id,super.getOrgi(request)) ;
			if(workOrders!=null){
				if(workOrders!=null && comment!=null && !StringUtils.isBlank(comment.getContent()) && Jsoup.parse(comment.getContent()).hasText()){
		    		comment.setId(UKTools.getUUID());
		    		comment.setCreater(super.getUser(request).getId());
		    		comment.setOrgi(super.getOrgi(request));
		    		comment.setDataid(workOrders.getId());
		    		if(!StringUtils.isBlank(comment.getDataid())){
		    			comment.setDataid(id);
		    		}
		    		comment.setCreatetime(new Date());
		    		ordersCommentRes.save(comment) ;
		    		
		    		/**
		    		 * 数据变更记录
		    		 */
		    		DataEvent event = new DataEvent();
		    		event.setDataid(workOrders.getId());
					event.setCreater(super.getUser(request).getId());
					event.setOrgi(super.getOrgi(request));
					event.setModifyid(UKTools.genID());
					event.setCreatetime(new Date());
		        	event.setCreatetime(new Date());
		        	event.setName("comment");
		        	
		        	String text = Jsoup.parse(comment.getContent()).text() ;
		        	if(text.length() > 200){
		        		event.setContent(text.substring(0, 200));
		        	}else if(text.length() > 0){
		        		event.setContent(text);
		        	}
		        	
		        	if(files!=null && files.length > 0){
	            		UKTools.processAttachmentFile(files, attachementRes , path, super.getUser(request) , super.getOrgi(request), workOrders, request, comment.getId(), workOrders.getId());
	            	}
		        	
		        	dataEventRes.save(event) ;
		    	}
			}else{
				result.setStatus(RestResultType.WORKORDERS_NOTEXIST);
			}
		}
        return new ResponseEntity<>(result, HttpStatus.OK);
    }
	
	@RequestMapping(value="/list")
	@Menu(type = "apps" , subtype = "user" , access = true)
	@ApiOperation("返回指定工单的回复列表")
    public ResponseEntity<RestResult> list(HttpServletRequest request , @Valid String id) {
		WorkOrders workOrders = workOrdersRes.findByIdAndOrgi(id,super.getOrgi(request)) ;
		Page<OrdersComment> commentList = null;
		if(workOrders!=null){
    		commentList = getCommentList(workOrders, request);
    	}
		 return new ResponseEntity<>(new RestResult(RestResultType.OK, new SearchData<OrdersComment>(commentList)), HttpStatus.OK);
    }
	
	 public Page<OrdersComment> getCommentList(WorkOrders workOrders , HttpServletRequest request ){
	    	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	    	
	    	BoolQueryBuilder myBuilder = QueryBuilders.boolQuery();
	    	myBuilder.must(termQuery("dataid" , workOrders.getId())) ;
	    	myBuilder.must(termQuery("orgi" , super.getOrgi(request))) ;
	    	
	    	boolQueryBuilder.must(myBuilder) ;
	    	
	    	return ordersCommentRes.findByQuery(boolQueryBuilder, null , new PageRequest(super.getP(request), super.getPs(request) , Direction.DESC , "createtime"));
	    }
	    
}